#pragma once
#include<iostream>
#include<string>
#include<functional>
#include<strings.h>
#include<unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include <arpa/inet.h>
#include"LOG.hpp"
#include"InetAddr.hpp"
#include"Socket.hpp"

using namespace socket_ns;
class TcpServer;
using io_service_t = std::function<void (socket_ptr sockfd,InetAddr client)>;



class ThreadData
{
public:
    ThreadData(socket_ptr fd,InetAddr addr,TcpServer *s):sockfd(fd),clientaddr(addr),self(s)
    {}
public:
    socket_ptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};
class TcpServer
{
public:
    //构造
    
    TcpServer(int port,io_service_t service)
        :_localaddr("0",port),_service(service)
        ,_listensock(std::make_unique<TcpSocket>())
        ,_isrunning(false)
    {
        //直接套接字构建绑定监听
        _listensock->BuildListenSocket(_localaddr);
    }
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        ::close(td->sockfd->SockFd()); 
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr peeraddr;
            socket_ptr normalsock =_listensock->Accepter(&peeraddr);
            if(normalsock == nullptr)   continue;
            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HandlerSock, td);

        }
        _isrunning = false;
    }
    //析构
    ~TcpServer()
    {
    }
private:
    bool _isrunning;
    std::unique_ptr<Socket> _listensock;
    InetAddr _localaddr;
    io_service_t _service;
};